﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TcpSyncIMServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        public bool appRun = true;
        private Listener lis;
        private Sender sen;

        string netIp;
        string chatIp;
        string myip;
        IPAddress myscanip;

        /// <summary>
        /// 返回信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="addMessageEventArgs"></param>
        public void AddMessage(object sender, AddMessageEventArgs addMessageEventArgs) {
            string message = addMessageEventArgs.Message;
            string appendText;
            string[] sep = message.Split('>');
            string[] sepIp = sep[0].Split('<', ':');
            bool checkIp = true;
            for (int i = 0; i < listBox1.Items.Count; i++) {
                if (listBox1.Items[i].ToString() == sepIp[1]) {
                    checkIp = false;
                }
                if (checkIp && sep[1] != "断开") {
                    this.listBox1.Items.Add(sepIp[1].Trim());
                    chatIp = sepIp[1];
                }
                appendText = sep[0] + ">" + System.DateTime.Now.ToString() + Environment.NewLine + sep[1] + Environment.NewLine;
                int txtGetMsgLength = this.richTextBox1.Text.Length;
                this.richTextBox1.AppendText(appendText);
                this.richTextBox1.Select(txtGetMsgLength, appendText.Length - Environment.NewLine.Length * 2 - sep[1].Length);
                this.richTextBox1.SelectionColor = Color.Red;
                this.richTextBox1.ScrollToCaret();
            }
        }

        /// <summary>
        /// 下线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="addMessageEventArgs"></param>
        public void IpRemo(object sender, AddMessageEventArgs addMessageEventArgs) {
            string[] sep = addMessageEventArgs.Message.Split(".");
            try
            {
                int index = 0;
                for (int i = 0; i < listBox1.Items.Count; i++) {
                    if (listBox1.Items[i].ToString() == sep[0].ToString()) {
                        index = i;
                        this.listBox1.Items.RemoveAt(index);
                    }
                }
            }
            catch {
                MessageBox.Show("没有这个IP");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex < 0 && chatIp == "" && chatIp == null)
            {
                MessageBox.Show("请选择目标主机");
                return;
            }
            else if (richTextBox2.Text.Trim() == "")
            {
                MessageBox.Show("消息内容不能为空!", "错误");
                this.richTextBox2.Focus();
                return;
            }
            else {
                try
                {
                    sen = new Sender(chatIp);
                    sen.Send(richTextBox2.Text);
                    string appendText;
                    appendText = "Me:" + System.DateTime.Now.ToString() + Environment.NewLine + richTextBox2.Text + Environment.NewLine;
                    int txtGetMsgLength = this.richTextBox1.Text.Length;
                    this.richTextBox1.AppendText(appendText);
                    this.richTextBox1.Select(txtGetMsgLength, appendText.Length - Environment.NewLine.Length * 2 - richTextBox2.Text.Length);
                    this.richTextBox1.SelectionColor = Color.Blue;
                    this.richTextBox1.ScrollToCaret();
                }
                catch { 
                
                }
                this.richTextBox2.Text = "";
                this.richTextBox2.Focus();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.start_listener();
            this.toolStripStatusLabel1.Text = "监听已启动      ";
        }
        /// <summary>
        /// 连接
        /// </summary>
        private void start_listener()
        {
            try
            {
                if (lis.lisenerRun == true) {
                    lis.lisenerRun = false;
                    lis.Stop();
                }
            }
            catch (NullReferenceException) {
                lis = new Listener();
                lis.OnAddMessage += new EventHandler<AddMessageEventArgs>(this.AddMessage);
                lis.OnIpRemod += new EventHandler<AddMessageEventArgs>(this.IpRemo);
                lis.StartLisener();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                lis.lisenerRun = false;
                lis.Stop();
                this.toolStripStatusLabel1.Text = "监听已停止   ";
            }
            catch (NullReferenceException) {

            }
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {  
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            netIp = getNetId();//网关
            this.label1.Text = "本主机ip是:" + GetMyIpAddress();
        }

        string getNetId() {
            string NetId;
            string ip = GetMyIpAddress();
            NetId = ip.Substring(0, ip.LastIndexOf(".") + 1);
            return NetId;
        }

        /// <summary>
        /// 获取本机ip
        /// </summary>
        /// <returns></returns>
        private static string GetMyIpAddress()
        {
            IPAddress iPAddress = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
            return iPAddress.ToString();

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="mouseEventArgs"></param>
        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs mouseEventArgs) {
            if (mouseEventArgs.Clicks != 0) {
                if (listBox1.SelectedItem != null) {
                    this.start_listener();
                    chatIp = listBox1.SelectedItem.ToString();
                }
            }
        }
    }
}
